package com.security;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用来处理登录请求
 */
@Component
public class LoginAuthenticationFilter extends OncePerRequestFilter {
    @Autowired
    @Lazy
    AuthenticationManager authenticationManager;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String code = request.getHeader("code");
        Authentication authentication = null;
        String username = request.getParameter("username");
        if (StringUtils.isEmpty(code)) {//第一次登陆，用户名密码登陆
            String password = request.getParameter("password");
            authentication = new UserPasswordAuthentication(username, password, true);
        } else {//第二次登陆，otp登陆
            Boolean rememberMe = Boolean.valueOf(request.getParameter("rememberMe"));
            authentication = new OtpAuthentication(username, code, rememberMe);
        }
        //委托manager进行认证
        Authentication authenticate = authenticationManager.authenticate(authentication);
        if (authenticate != null) {
            //设置响应状态为200
            response.setStatus(response.SC_OK);
            //第二次验证成功之后，调用OtpAuthentication三个参数的方法则isAuthenticated为true
            if (authenticate.isAuthenticated()) {
                String string = JSON.toJSONString(authenticate.getPrincipal());
                //将令牌存入响应头
                response.setHeader("Authorization", JSON.toJSONString(authenticate.getPrincipal()));
            }
        } else {
            response.setStatus(response.SC_BAD_REQUEST); //认证失败
        }
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        return !request.getServletPath().equals("/login");
    }
}
